<template>
  <div class="list-header">
    <!--
    <div v-if="!isHideSidebar && hasRouteAuth('crm:chatGpt:read')" :style="{width: showMobilePage ? '' : '85px'}" class="help" style="margin-left: 16px;" @click="toChatGpt">
      <template v-if="!showMobilePage">
        <img :src="chatGptIcon" class="helpIcon" alt="chatIcon">
        <img :src="chatGptIconActive" class="helpIconActive" alt="chatIcon">
      </template>
      <img v-else :src="chatIcon" class="img" alt="chatIcon">
      <span v-if="!showMobilePage" class="mobile-tip-text">ChatGPT</span>
    </div>
    -->
    <el-popover
      ref="todoPopper"
      v-model="helpVisible"
      :width="showMobilePage ? 300 : 400"
      :class="{'mobile-header-wrap':showMobilePage}"
      placement="bottom"
      trigger="click"
      popper-class="notice-popper"
      @show="getNoticeData">
      <SwitchTab :active="activeId" :data="noticeTab" :font-size="'14px'" class="notice-tab" @switchTab="switchTab"/>
      <div v-loading="loading" class="notice-table">
        <el-table
          v-el-table-infinite-scroll="loadmore"
          v-if="noticeData && noticeData.items && noticeData.items.length > 0"
          :data="noticeData ? noticeData.items : []"
          :show-header="false"
          height="450"
          @row-click="toDetail">
          <template v-for="(settingItem, index) in globalNoticeField">
            <el-table-column :key="index" v-bind="globalNoticeRowField[settingItem.field]">
              <template slot-scope="scope">
                <template v-if="settingItem.field === 'proposerName'">
                  <div class="color-status-box">
                    <span v-if="activeId === 'notice' && !scope.row.read" class="dot"/>
                    <img :src="scope.row.avatar || avatarPng" class="column-creator-img" alt="发起人">
                  </div>
                </template>
                <template v-if="settingItem.field === 'abstract'">
                  <div>
                    <ToolTip :content="formatTitle(scope.row)" class="notice-title" />
                    <template v-if="strJsonParse(scope.row.content)">
                      <div v-for="(val, name) in formatAbstractData(scope.row.content)" :key="name">
                        <el-tooltip placement="top-start">
                          <div slot="content" style="max-width: 300px;">{{ `${name}：${val}` }}</div>
                          <div class="ellipsisOne" style="font-size: 12px">
                            <span style="color: #999">{{ name }}：</span>
                            <span>{{ (val || val === 0) ? val : '--' }}</span>
                          </div>
                        </el-tooltip>
                      </div>
                    </template>
                    <p v-if="scope.row.approvers">
                      <span>当前处理人：</span>
                      <ToolTip :content="scope.row.approvers" />
                    </p>
                    <p v-if="activeId === 'todo'"><span>{{ scope.row.type===6?'通知时间：':'发起时间：' }}</span>{{ formatTime(scope.row.createTime) }}</p>
                    <p v-if="activeId === 'notice'"><span>{{ scope.row.hasOwnProperty('month')?'通知时间：':'发起时间：' }}</span>{{ formatTime(scope.row.publicDate) }}</p>
                  </div>
                </template>
                <template v-if="settingItem.field === 'status'">
                  <p :style="{color: formatStatus(scope.row, 'notice').color}" class="flowstatus">{{ formatStatus(scope.row, 'notice').status }}</p>
                </template>
              </template>
            </el-table-column>
          </template>
          <p v-if="noticeData.items.length > 6" slot="append" class="load-more">{{ !isMax ? '向下滚动加载更多↓' : '没有更多数据了~' }}</p>
        </el-table>
        <div v-if="noticeData.items.length === 0 && activeId === 'todo'" class="no-data no-todo-data">
          <img :src="noTodo" alt="no-todo-data">
          <p>暂无待办项，处理效率很高噢~</p>
        </div>
        <div v-if="noticeData.items.length === 0 && activeId === 'notice'" class="no-data no-notice-data">
          <img :src="noNotice" alt="no-notice-data">
          <p>暂无通知消息~</p>
        </div>
      </div>
      <div class="notice-bottom">
        <div class="flex">
          <p v-if="activeId === 'todo'" class="to-todo" @click="toTodo"><span>前往待办中心</span> >></p>
          <el-checkbox
            v-if="activeId === 'todo'"
            v-model="isExpedited"
            :true-label="1"
            :false-label="0"
            class="checkbox-class"
            @change="setOnlyExpedited">仅展示加急</el-checkbox>
        </div>
        <p v-if="activeId === 'notice'" :class="{'disable-to-read': noticeData.items.length === 0 }" class="to-todo" @click="setALLRead">全部标记为已读</p>
      </div>
      <div v-if="!isHideSidebar" slot="reference" :style="{color: helpVisible ? '#406EFF' : '#666', width: showMobilePage ? '' : '55px'}" :class="{'notice-icon rel': showMobilePage && noticeNum > 0}" class="help">
        <!-- <img :src="mobileNotice" class="img" alt="bellIcon"> -->
        <template v-if="!showMobilePage">
          <img :src="bellIcon" :style="{display: helpVisible ? 'none' : 'block'}" class="bellIcon" alt="bellIcon">
          <img :src="bellIconActive" :style="{display: helpVisible ? 'block' : 'none'}" class="helpIconActive bellIcon" alt="helpIcon">
        </template>
        <img v-else :src="mobileNotice" class="img" alt="bellIcon">
        <span v-if="noticeNum > 0 && !showMobilePage" class="item-badge">{{ noticeNum >= 99 ? '99+': noticeNum }}</span>
        <span v-if="!showMobilePage" class="mobile-tip-text">通知</span>
      </div>
    </el-popover>
    <div v-if="!isHideSidebar" :style="{width: showMobilePage ? '' : '55px'}" class="help" @click="showHelp">
      <template v-if="!showMobilePage">
        <img :src="helpIcon" class="helpIcon" alt="helpIcon">
        <img :src="helpIconActive" class="helpIconActive" alt="helpIcon">
      </template>
      <img v-else :src="mobileHelp" class="img" alt="helpIcon">
      <span v-if="!showMobilePage" class="mobile-tip-text">帮助</span>
    </div>
    <el-drawer
      :visible.sync="isShowHelp"
      :with-header="false"
      :custom-class="`${showMobilePage?'mobile-process-drawer':''} process-drawer`"
      :modal-append-to-body="false"
      :direction="showMobilePage?'ltr':'rtl'">
      <div style="height: 100vh;overflow: auto">
        <helpDialog :router-name="routerName" :is-show-help="isShowHelp" @closeDialog="closeDialog"/>
      </div>
    </el-drawer>

    <el-dropdown class="avatar-container" trigger="click">
      <div class="list-avatar">
        <img :src="avatar ? avatar : defaultAvatar" class="avatar-img" alt="用户头像">
      </div>
      <el-dropdown-menu slot="dropdown" class="user-dropdown">
        <el-dropdown-item class="num-set" @click.native="showDingdingDialog">
          <div class="dropdown-item-bar">
            <img :src="headerDingding" class="icon-img" style="width:14px;" alt="headerDingding">
            <img :src="headerDingdingActive" class="icon-img-active" style="width:14px;" alt="headerDingdingActive">
            <div>推送飞书</div>
          </div>
        </el-dropdown-item>
        <router-link :to="{ name:'userDetail', params: { userId: id } }" class="inlineBlock" target="_blank">
          <el-dropdown-item class="num-set">
            <div class="dropdown-item-bar">
              <img :src="headerSetting" class="icon-img" style="width:16px;" alt="headerSetting">
              <img :src="headerSettingActive" class="icon-img-active" style="width:16px;" alt="headerSettingActive">
              <div class="label">用户信息</div>
            </div>
          </el-dropdown-item>
        </router-link>
        <router-link v-if="hasPermission" :to="{ name:'editOperator', params: { operatorId: id } }" class="inlineBlock" target="_blank">
          <el-dropdown-item class="num-set">
            <div class="dropdown-item-bar">
              <img :src="permission" class="icon-img" style="width:16px;" alt="permission">
              <img :src="permissionActive" class="icon-img-active" style="width:16px;" alt="permission-active">
              <div class="label">个人权限</div>
            </div>
          </el-dropdown-item>
        </router-link>
        <el-dropdown-item v-if="isMobile && isShowSwitch" class="back-set">
          <div class="dropdown-item-bar" @click="handelSwitchMobile">
            <img :src="headerSetting" class="icon-img" style="width:16px;" alt="">
            <div class="label">切换{{ showMobilePage?'PC端':'移动端' }}</div>
          </div>
        </el-dropdown-item>
        <el-dropdown-item class="back-set">
          <div class="dropdown-item-bar" @click="logout">
            <img :src="headerLogout" class="icon-img" style="width:16px;" alt="headerLogout">
            <img :src="headerLogoutActive" class="icon-img-active" style="width:16px;" alt="headerLogoutActive">
            <div class="label">退出登录</div>
          </div>
        </el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
    <dingTalkMessage ref="dingTalkMessageRef" :is-show-btn="false" />
  </div>
</template>

<script>
import { mapGetters, mapState } from 'vuex';
import headerDingdingActive from '@/assets/header_dingding_active.png';
import headerSettingActive from '@/assets/header_setting_active.png';
import permissionActive from '@/assets/setting/permission_active.png';
import headerLogoutActive from '@/assets/header_logout_active.png';
import helpIconActive from '@/assets/help/help_active.png';
import bellIconActive from '@/assets/todo/bellActive.png';
import headerDingding from '@/assets/header_dingding.png';
import permission from '@/assets/setting/permission.png';
import headerSetting from '@/assets/header_setting.png';
import headerLogout from '@/assets/header_logout.png';
import defaultAvatar from '@/assets/user-avatar.png';
import noNotice from '@/assets/todo/noNotice.png';
import helpIcon from '@/assets/help/help.png';
import chatIcon from '@/assets/chat-icon.png';
import chatGptIcon from '@/assets/chatGptIcon.png';
import chatGptIconActive from '@/assets/chatGptIconActive.png';
import bellIcon from '@/assets/todo/bell.png';
import noTodo from '@/assets/empty-table-data.png';
import mobileHelp from '@/assets/mobileIcon/help.png';
import mobileNotice from '@/assets/mobileIcon/notice.png';
import dingTalkMessage from '@/components/Common/dingTalkMessage';
import helpDialog from '@/components/helpCenter/helpDialog';
import SwitchTab from '@/views/customer/module/switchTab';
import { getList, getReceiveList, setListRead } from '@/api/todo';
import { hasRouteAuth } from '@/utils/permission';
import { showModal } from '@/utils/message';
import { switchMobile, isMobile as getIsMobile } from '@/utils/tools';
import { EventBus } from '@/utils/eventBus';
import { strJsonParse } from '@/utils';
import Todo from '@/mixins/todo';
import axios from 'axios';
import { globalNoticeField, globalNoticeRowField } from '@/views/todo/fieldData';

export default {
  components: { helpDialog, dingTalkMessage, SwitchTab },
  mixins: [Todo],
  data() {
    return {
      mobileHelp, mobileNotice,
      defaultAvatar, headerSetting, headerLogout, helpIcon, headerDingding,
      headerSettingActive, headerLogoutActive, headerDingdingActive, helpIconActive,
      bellIcon,
      chatIcon,
      chatGptIcon,
      chatGptIconActive,
      bellIconActive,
      permission,
      permissionActive,
      helpVisible: false,
      isShowHelp: false,
      activeId: 'todo',
      noticeTab: [{
        name: '待办',
        class: 'todo',
        num: 0
      }, {
        name: '通知',
        class: 'notice',
        num: 0
      }],
      loading: false,
      noticeData: {
        items: []
      },
      noNotice,
      noTodo,
      receiveListCancelToken: null,
      listCancelToken: null,
      globalNoticeField,
      globalNoticeRowField,
      isExpedited: 0
    };
  },
  computed: {
    ...mapGetters([
      'id',
      'userName',
      'deptName',
      'noticeNum',
      'sidebar'
    ]),
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'avatar': state => state.user.avatar,
      'showMobilePage': state => state.app.showMobilePage,
      'mobilePage': state => state.app.mobilePage
    }),
    isMobile() {
      return getIsMobile();
    },
    isHideSidebar() { // 用于判断顶部的共创平台点击跳转为跳回首页
      return this.$route.meta.isHideSidebar;
    },
    routerName() {
      return this.$route.name;
    },
    isMax() {
      return this.noticeData.items.length >= this.noticeData.total;
    },
    disableToRead() {
      return this.noticeData.items.length;
    },
    isShowSwitch() {
      return this.mobilePage.includes(this.routerName);
    },
    hasPermission() {
      // (角色可读 && 操作员可读) && (编辑 || 全向编辑)
      return (hasRouteAuth('auth:role:read') && hasRouteAuth('auth:operator:read')) && (hasRouteAuth('auth:operator:edit') || hasRouteAuth('auth:operator:adminEdit'));
    }
  },
  methods: {
    strJsonParse,
    toChatGpt() {
      if (this.sidebar.opened) {
        this.$store.dispatch('CloseSideBar', { withoutAnimation: false });
      }
      this.$router.push({ name: 'chatGptPage' });
    },
    async getReceiveTab() {
      try {
        const params = {
          page: 1,
          perPage: 20,
          isExpedited: this.isExpedited,
          tabStatus: 0
        };
        const params1 = {
          page: 1,
          perPage: 20,
          tabStatus: 3,
          onlyUnread: 1
        };
        const res = await getList(params);
        const result = await getReceiveList(params1);
        this.noticeTab[0].num = res.data.total;
        this.noticeTab[1].num = result.data.total;
        if (!this.isExpedited) {
          this.$store.commit('SETNOTICENUM', { total: res.data.total, unTotal: result.data.total });
        }
      } catch (error) {
        console.log(error);
      }
    },
    logout() {
      this.$store.dispatch('LogOut').then(() => {
        // location.reload(); // 为了重新实例化vue-router对象 避免bug
        location.href = '/';
      });
    },
    showDingdingDialog() {
      this.$refs.dingTalkMessageRef.showDialog();
    },
    showHelp() {
      this.isShowHelp = true;
    },
    closeDialog() {
      this.isShowHelp = false;
    },
    switchTab(val) {
      this.activeId = val;
      this.noticeData.items = [];
      this.getNoticeData();
    },
    async getNoticeData(page = 1, concat = false) {
      this.getReceiveTab();
      this.loading = true;
      const params = {
        page: page,
        perPage: 10
      };
      let res = {};
      if (this.activeId === 'todo') {
        if (this.receiveListCancelToken) this.receiveListCancelToken.cancel('cancel');
        if (this.listCancelToken) this.listCancelToken.cancel('cancel');
        const source = axios.CancelToken.source();
        this.listCancelToken = source;
        params.tabStatus = 0;
        params.isExpedited = this.isExpedited;
        res = await getList(params, source.token);
      } else if (this.activeId === 'notice') {
        params.onlyUnread = 1;
        if (this.listCancelToken) this.listCancelToken.cancel('cancel');
        if (this.receiveListCancelToken) this.receiveListCancelToken.cancel('cancel');
        const source = axios.CancelToken.source();
        this.receiveListCancelToken = source;
        res = await getReceiveList(params, source.token);
        const data = res.data.items;
        if (data.length > 0) {
          res.data.items = data.map(item => {
            if (item.extendStr && this.isJSON(item.extendStr)) {
              const urlObj = JSON.parse(item.extendStr);
              item = { ...item, ...urlObj };
            }
            if (item.abstractStr && typeof item.abstractStr === 'string') {
              item.abstractStr = item.abstractStr.replace(/\n/g, '');
            }
            if (item.abstractStr && this.isJSON(item.abstractStr)) {
              const urlObj = JSON.parse(item.abstractStr);
              item = { ...item, ...urlObj };
            }
            return item;
          });
        }
      }
      if (res.data && res.data.items && res.data.items.length > 0) {
        res.data.items = concat ? this.noticeData.items.concat(res.data.items) : res.data.items;
      }
      this.noticeData = res.data || { items: [] };
      this.loading = false;
    },
    toTodo() {
      const url = this.$router.resolve({ name: 'todo' });
      window.open(url.href, '_blank');
    },
    setALLRead() {
      if (this.noticeData.items.length > 0) {
        showModal('请确认是否全部标记为已读', '', {
          iconClass: 'del-icon'
        }).then(() => {
          this.noticeData = { items: [] };
          this.setListRead(-1);
        }).catch(() => {
          return false;
        });
      }
    },
    async setListRead(id) {
      await setListRead(id);
      if (id === -1) {
        this.getNoticeData();
        EventBus.$emit('setAllRead', '标记全部为已读');
      }
    },
    loadmore() {
      if (this.noticeData.items) {
        if (!this.isMax && !this.loading) {
          this.getNoticeData(this.noticeData.page + 1, true);
        }
      }
    },
    async setSingleRead(row) {
      if (this.activeId === 'notice' && !row.read) {
        await this.setListRead(row.id);
        const index = this.noticeData.items.findIndex(item => {
          return item.id === row.id;
        });
        this.noticeData.items[index].read = true;
        const item = this.noticeData.items[index];
        this.$set(this.noticeData.items, index, item);
      }
    },
    handelSwitchMobile() {
      switchMobile(this.$route.name);
    },
    setOnlyExpedited(val) {
      this.isExpedited = val;
      this.getNoticeData();
    }
  }
};
</script>

<style lang="scss" scoped>
.list-header {
  display:flex;
  height: 48px;
  align-items: center;
  .chat {
    position: relative;
    cursor: pointer;
    font-size: 14px;
    font-weight: 400;
    display:flex;
    align-items: center;
    color: #666666;
    margin-right:16px;
    &:hover {
      color: #406EFF !important;
      .chatIcon {
        display: none !important;
      }
      .chatIconActive {
        display: block !important;
      }
    }
    .chatIconActive {
      display: none;
    }
  }
  .help {
    position: relative;
    cursor: pointer;
    font-size: 14px;
    font-weight: 400;
    display:flex;
    align-items: center;
    color: #666666;
    margin-right:16px;
    &:hover {
      color: #406EFF !important;
      .helpIcon, .bellIcon {
        display: none !important;
      }
      .helpIconActive {
        display: block !important;
      }
    }
    .helpIconActive {
      display: none;
    }
    i {
      font-size:18px;
      color: #192452;
    }
    img {
      width: 16px;
      margin-right:4px;
      height: 16px;
    }
    .bellIcon {
      width: 12px;
      height: 12px;
    }
    .item-badge {
      position: absolute;
      top: -10px;
      right: -5px;
      padding: 0 2px;
      height: 18px;
      min-width: 18px;
      line-height: 18px;
      text-align: center;
      border-radius: 10px;
      background-color: #FB5227;
      font-size: 10px;
      display: inline-block;
      color: #fff;
      transform: scale(0.9);
      margin-left: 4px;
      font-weight: 500;
    }
  }
}
.mobile-header-wrap {
  .mobile-tip-text {
    color: #fff;
  }
  .notice-icon::before {
    content: '';
    top: -1px;
    right: 2px;
    width: 6px;
    height: 6px;
    background: #FB5227;
    border-radius: 50%;
    position: absolute;
  }
}
.notice-table {
  & ::v-deep {
    .el-table {
      &::v-deep .el-table__row:hover {
        cursor: pointer !important;
      }
      .notice-title {
        font-size: 14px;
        color: #333;
        font-weight: bold;
      }
      p {
        display: flex;
        align-items: center;
        line-height: 18px;
        font-size: 12px;
        // font-weight: bold;
        margin: 0;
        color: #666;
        cursor: pointer !important;
        white-space: nowrap;
        .notice-title {
          font-size: 14px;
          color: #333;
          font-weight: bold;
        }
        &.flowstatus {
          font-size: 14px;
          font-weight: bold;
        }
        &.notice-content, .notice-content {
          font-size: 12px;
          font-weight: normal;
          color: #666;
        }
        .notice-content, .notice-title {
          display: inline-block;
          width: auto;
        }
        span {
          font-weight: normal;
          color: #999;
        }
      }
      .cell {
        padding: 0 !important;
      }
      .dot {
        left: 4px;
      }
      .el-avatar {
        margin: 0 8px 0 12px;
        cursor: pointer !important;
      }
      .flowStatus {
        margin: 0 15px 0 7px;
      }
      .load-more {
        justify-content: center;
        margin: 0;
        padding: 4px 0;
        background-color: #F5F5F5;
        color: #999;
        font-weight: normal;
      }
      .column-creator-img {
        width: 48px;
        height: 48px;
        margin: 0 8px 0 12px;
        border-radius: 100%;
      }
    }
  }
}

.user-dropdown {
  margin-top: 6px!important;
  width: 120px;
  padding: 0!important;
  .dropdown-item-bar {
    color: #666;
    font-size: 14px;
    white-space: nowrap;
    display: flex;
    align-items: center;
    img {
      margin-right: 6px;
    }
  }
  &::v-deep {
    .el-dropdown-menu__item {
      height: 47px;
      display: flex;
      align-items: center;
      padding: 0 9px;
      background-color: #fff;
      .icon-img-active {
        display: none;
      }
      &:hover {
        .dropdown-item-bar {
          color: #406EFF;
        }
        .icon-img {
          display: none;
        }
        .icon-img-active {
          display: block;
        }
      }
    }
    .el-collapse-item__header {
      padding: 0 4px 0 20px;
      border-bottom: none;
    }
    .el-collapse-item__wrap {
      border-bottom: none;
    }
    .dropdown-item-bar {
      color: #666;
      font-weight: 400;
    }
    .el-collapse-item__content {
      padding-bottom: 0px;
    }
  }
}
.list-avatar {
  cursor: pointer;
  display: flex;
  align-items: center;
  img {
    width:24px;
    height:24px;
    border-radius: 100%;
    border: 2px solid #fff;
  }
  .name {
    font-size:16px;
    font-family:PingFangSC-Regular,PingFang SC;
    font-weight:400;
    color:#333333;
    margin-left: 12px;
  }
}
.notice-tab {
  padding: 15px 0 0 24px;
  border-bottom: 1px solid #F5F5F5;
}
.no-data {
  height: 442px;
  text-align: center;
  img {
    width: 120px;
    height: auto;
    margin-top: 100px;
  }
  p {
    margin-top: 16px;
    font-size: 14px;
    color: #999;
  }
}
.notice-bottom {
  height: 40px;
  line-height: 40px;
  padding: 0 16px;
  font-size: 14px;
  cursor: pointer;
  border-top: 1px solid #f5f5f5;
  p{
    margin: 0;
    color: #333;
  }
  .to-todo {
    color: #406EFF;
    span {
      text-decoration: underline;
    }
  }
  .disable-to-read {
    color: #999;
    &:hover {
      cursor: not-allowed;
    }
  }
  .flex {
    justify-content: space-between;
  }
}
</style>
<style lang="scss">
.el-popper.notice-popper {
  padding: 0 !important;
}
.list-header {
  .mobile-process-drawer {
    max-width: 380px!important;
    width: 90%!important;
  }
}
</style>
